package com.hospicpc.demos.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.hospicpc.demos.commom.Result;
import com.hospicpc.demos.entity.Articles;
import com.hospicpc.demos.entity.ArticlesAi;
import com.hospicpc.demos.entity.User;
import com.hospicpc.demos.entity.dto.ArticleAiDto;
import com.hospicpc.demos.entity.dto.ArticleDto;
import com.hospicpc.demos.entity.vo.ArticleVo;
import com.hospicpc.demos.mapper.ArticleVoMapper;
import com.hospicpc.demos.service.Impl.ArticlesAiServiceImpl;
import com.hospicpc.demos.service.Impl.ArticlesServiceImpl;
import com.hospicpc.demos.utils.RandomNumber;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Random;

import static com.hospicpc.demos.utils.JwtUtil.getUserIdByJWT;

@RestController
@RequestMapping("/articles")
public class ArticlesController {

    @Autowired
    ArticleVoMapper articleVoMapper;
    final
    ArticlesServiceImpl articlesService;
    final
    ArticlesAiServiceImpl articlesAiService;

    public ArticlesController(ArticlesServiceImpl articlesService,ArticlesAiServiceImpl articlesAiService) {
        this.articlesService = articlesService;
        this.articlesAiService = articlesAiService;
    }

    /**
     * 通过id随机获取文章
     * @param id
     */
    @GetMapping("/getRandomById")
    public Result getRandomById(@RequestParam("id") Long id, HttpServletRequest httpServletRequest) {

        //获取userId
        Long userId = Long.valueOf(getUserIdByJWT(httpServletRequest));

        //判断ai文章是否存在
        ArticlesAi aiA = articlesAiService.lambdaQuery().eq(ArticlesAi::getArticleId,id).one();

        //如果为空，直接返回普通文章
        if(aiA == null) {
            //获取普通文章
            Articles a = articlesService.getById(id);
            ArticleVo av = articleVoMapper.getArticleInfo(userId, a.getId(), a.getAuthorId(), 1L);
            ArticleDto articleDto = new ArticleDto(av.getFollowAuthor(),av.getCollectArticle(),av.getLikeArticle());
            //使用hutool工具完成实体类与dto类的转化
            BeanUtil.copyProperties(a,articleDto);
            return Result.success(articleDto);
        }

        //获取普通文章
        Articles a = articlesService.getById(id);

        //不为空,随机返回其中一个文章
        boolean b = new Random().nextBoolean();
        if( b ) {
            ArticleVo av = articleVoMapper.getArticleInfo(userId, a.getId(), aiA.getAuthorId(), 0L);
            ArticleAiDto articleAiDto = new ArticleAiDto(av.getFollowAuthor(),av.getCollectArticle(),av.getLikeArticle());
            BeanUtil.copyProperties(aiA,articleAiDto);
            articleAiDto.setAuthorName(a.getAuthorName());articleAiDto.setTitle(a.getTitle());articleAiDto.setDescription(a.getDescription());
            return  Result.success(articleAiDto);
        } else {
            ArticleVo av = articleVoMapper.getArticleInfo(userId, a.getId(), a.getAuthorId(), 1L);
            ArticleDto articleDto = new ArticleDto(av.getFollowAuthor(),av.getCollectArticle(),av.getLikeArticle());
            //使用hutool工具完成实体类与dto类的转化
            BeanUtil.copyProperties(a,articleDto);
            return Result.success(articleDto);
        }

    }

    /**
     * 根据获取指定文章
     * @param id
     * @param articleType
     * @return
     */
    // @GetMapping("/getById")
    // public Result getById(@RequestParam("id") Long id,@RequestParam("articleType") Integer articleType,HttpServletRequest httpServletRequest) {
    //
    //     //获取userId
    //     Long userId = Long.valueOf(getUserIdByJWT(httpServletRequest));
    //
    //
    //
    // }



    /**
     * 倒叙表分页获取文章列表
     * @return
     */
    @GetMapping("/getListPage")
    public  Result getListPage(@RequestParam("page") Integer page,@RequestParam("pageNumber") Integer pageNumber) {

        //获取文章表数量
        Integer count = articlesService.count();

        //计算分页查询起始位置
        page = count - (pageNumber * page);

        //判断数据取完的情况
        if(page < -pageNumber) return Result.success("无数据");

        List<Articles> lists = articlesService.getListPage(page, pageNumber);

        return Result.success(lists);

    }

    /**
     * 根据用户id获取文章列表
     * @param userId
     * @return
     */
    @GetMapping("/getListByUserId")
    public  Result getListByUserId(@RequestParam("userId") Long userId) {
        List<Articles> list = articlesService.lambdaQuery().select(Articles::getId, Articles::getTitle, Articles::getAuthorName)
                .eq(Articles::getAuthorId, userId)
                .orderByDesc(Articles::getId)
                .list();

        return Result.success(list);
    }

    /**
     * 根据文章分类获取文章列表
     */
    @GetMapping("/getListByCategoryType")
    public  Result getListByArticleType(@RequestParam("id") int articleCategoryId) {
        System.out.println("articleCategoryId = " + articleCategoryId);
        List<Articles> list = articlesService.lambdaQuery()
                .eq(Articles::getCategory, articleCategoryId)
                .orderByDesc(Articles::getId)
                .list();
        return Result.success(list);
    }

    /**
     * 添加一条文章
     */
    @PostMapping("/addArticle")
    public Result addArticle(@RequestBody Map<String,Object> map) {
        Articles articles = new Articles();
        articles.setTitle((String) map.get("title"));
        articles.setDescription((String) map.get("description"));
        articles.setAuthorId(Long.valueOf((String) map.get("authorId")));
        articles.setAuthorName((String) map.get("authorName"));
        articles.setContent((String) map.get("content"));
        boolean save = articlesService.save(articles);
        if (save)  return Result.success();
        else return Result.error("添加失败");
    }

    /**
     * 根据文章id删除文章
     */
    @DeleteMapping("/delete/{id}")
    public Result deleteArticle(@PathVariable(value = "id") Long id) {
        boolean b = articlesService.removeById(id);
        if (b) return Result.success();
        else return Result.error("删除失败");
    }
}
